package cn.com.libertymutual.web.filter;

import java.io.File;
import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UrlPathHelper;

import cn.com.libertymutual.core.base.dto.UserInfo;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.core.web.util.PathMatcherUtil;
import cn.com.libertymutual.core.web.util.RequestUtils;
import cn.com.libertymutual.core.web.util.ResponseUtils;

//@Component
//@WebFilter(filterName="sessionFilter",urlPatterns="/**", displayName="sessionFilter",description="判断是否登陆")
public class SessionFilter extends OncePerRequestFilter {

	private PathMatcherUtil pathMatcherUtil;
	private String[] excludeUris;
	private UrlPathHelper helper;
	private PathMatcher pathMatcher;

	private String loginPage = null;
	private String micMsgSessionInvalidatePage = null;
	private String logoutPage = null;
	private String loginProcessingUrl = null;

	public SessionFilter() {
		/// this.excludeUris = excludeUris;
		// pathMatcherUtil = new PathMatcherUtil( excludeUri );
		pathMatcherUtil = new PathMatcherUtil();
		helper = new UrlPathHelper();
		pathMatcher = new AntPathMatcher(File.separator);
	}

	@Override
	public void initFilterBean() throws ServletException {
	}

	public SessionFilter loginPage(String loginPage) {
		this.loginPage = loginPage;
		return this;
	}

	public SessionFilter micMsgSessionInvalidatePage(String micMsgSessionInvalidatePage) {
		this.micMsgSessionInvalidatePage = micMsgSessionInvalidatePage;
		return this;
	}

	public SessionFilter logoutPage(String logoutPage) {
		this.logoutPage = logoutPage;
		return this;
	}

	public SessionFilter loginProcessingUrl(String loginProcessingUrl) {
		this.loginProcessingUrl = loginProcessingUrl;
		return this;
	}

	public SessionFilter excludeUri(String[] excludeUri) {

		pathMatcherUtil.setPatterns(excludeUri);

		return this;
	}

	public void build() {
		pathMatcherUtil.addPatterns(loginProcessingUrl);
		pathMatcherUtil.addPatterns(logoutPage);
	}

	@Override
	public void destroy() {
		/**
		 * 停止线程池
		 */
		/// MessageTemplateExecutor.shutdown();
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		// System.out.println( helper.getLookupPathForRequest(request) );

		// String agentCode =
		// (String)request.getSession(true).getAttribute(Constants.SESSIONKEY_AGENTCODE);
		/*
		 * System.out.println( "agentCode = "+agentCode ); System.out.println(
		 * request.getRemoteAddr() ); System.out.println( request.getRemoteHost() );
		 * System.out.println( request.getLocalAddr()+"\t"+request.getLocalPort() );
		 * System.out.println( request.getScheme() ); System.out.println(
		 * request.getRequestURI() );
		 */
		/// System.out.println( request.getRequestURI() );
		/// System.out.println("zhixing " + helper.getLookupPathForRequest(request));
		// request.getUserPrincipal()
		UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constants.USER_INFO_KEY);
		// System.out.println(BeanUtilExt.toJsonString(userInfo));
		if (helper.getLookupPathForRequest(request).startsWith("/admin") && userInfo == null && !helper.getLookupPathForRequest(request).startsWith("/admin-cxb/callback") ) {
			// WebErrors error = WebErrorsUtil.create(
			// (HttpServletRequest)request );
			try {
				ResponseUtils.sendToClient((HttpServletResponse) response,
						new ServiceResult("登录超时,请重新登录", ServiceResult.STATE_NO_SESSION));
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}
		if (request.getUserPrincipal() == null
				&& !pathMatcherUtil.matches(helper.getLookupPathForRequest(request), pathMatcher)) {
			if (request.getUserPrincipal() == null && (RequestUtils.isRestRequest((HttpServletRequest) request))
					&& !pathMatcherUtil.matches(helper.getLookupPathForRequest(request), pathMatcher)) {

				// WebErrors error = WebErrorsUtil.create((HttpServletRequest) request);
				try {
					ResponseUtils.sendToClient((HttpServletResponse) response,
							new ServiceResult("数据请求失败", ServiceResult.STATE_NO_SESSION));
					// ResponseUtils.sendToClient((HttpServletResponse)response,
					// new
					// ServiceResult(error.getMessage("autumn.studio.session.invalid"),
					// ServiceResult.STATE_NO_SESSION));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return;
			}

			/*
			 * //ajax 访问 if (RequestUtils.isRestRequest( request ) ) { try {
			 * ResponseUtils.sendToClient((HttpServletResponse)response, new
			 * ServiceResult("登陆失效或未登陆", ServiceResult.STATE_NO_SESSION)); } catch
			 * (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
			 * return; } else {
			 * 
			 * String userAgent=request.getHeader("user-agent"); if(userAgent != null &&
			 * userAgent.contains("MicroMessenger") &&
			 * StringUtils.isBlank(request.getParameter("code")) ){//微信客户端
			 * request.getRequestDispatcher( micMsgSessionInvalidatePage ).forward(request,
			 * response); } else request.getRequestDispatcher( loginPage ).forward(request,
			 * response); //request.getRequestDispatcher( micMsgSessionInvalidatePage
			 * ).forward(request, response);
			 * 
			 * return; }
			 */
		}

		filterChain.doFilter(request, response);

	}

}
